package com.bac.rentmap.web.controller.ad.manage;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.image.FlatImage;
import com.bac.rentmap.ad.flat.image.FlatImageType;
import com.bac.rentmap.ad.flat.jdo.CachingJdoFlatAdDao;
import com.bac.rentmap.ad.flat.jdo.JdoFlatAdDao;
import com.bac.rentmap.ad.flat.jdo.JdoHelper;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.datastore.Key;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by osa on 3/19/2015.
 */
public class UploadFlatImageController extends com.bac.rentmap.web.controller.ad.add.UploadFlatImageController {
    private static final Logger log = Logger
            .getLogger(UploadFlatImageController.class.getName());
    private JdoFlatAdDao jdoFlatAdDao;
    private PersistenceManagerFactory persistenceManagerFactory;
    private JdoHelper jdoHelper;
    private CachingJdoFlatAdDao cachingJdoFlatAdDao;

    public ModelAndView uploadedThumbnail(HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
        ModelAndView res = super.uploadedThumbnail(request, response);
        if(!res.getModel().containsKey("flatImageId")){
            String flatImageId = request.getParameter("flatImageId");
            if(flatImageId != null && !flatImageId.isEmpty()) {
                FlatImage flatImage = flatImageService.getFlatImage(Long.valueOf(flatImageId));
                if(flatImage != null){
                    res.addObject("flatImageId", flatImage.getId());
                }
            }
        }
        return res;
    }

    @Override
    protected void deleteFlatImage(FlatImageType flatImageType, String secureId, PersistenceManager nullPersistenceManager){
        PersistenceManager persistenceManager = getPersistenceManager();
        FlatAd flatAd = null;
        boolean removed = false;
        try {
            flatAd = jdoFlatAdDao.loadBySecureId(secureId, persistenceManager);
            log.info("Deleting original image for flatAd " + flatAd.getId() + ", flatImageType: " + flatImageType);
            Key flatAdKey = jdoHelper
                    .convertToFlatAdKey(flatAd.getId());
            List<FlatImage> flatImageList = flatImageService.getFlatImages(flatAdKey, persistenceManager);
            for (Iterator<FlatImage> it = flatImageList.iterator(); it.hasNext();) {
                FlatImage flatImage = it.next();
                log.fine("type:" + flatImage.getType());
                if(flatImage.getType() == flatImageType){
                    log.info("Found original image " + flatImage.getId());
                    Key flatImageKey = jdoHelper.convertToFlatImageKey(flatImage.getId());
                    log.info("flatImageKey " + flatImageKey);
                    log.info("getFlatImages " + flatAd.getFlatImages());
                    removed = flatAd.getFlatImages().remove(flatImageKey);

                    log.info("removed: " + removed);
                    persistenceManager.deletePersistent(flatImage);
                    return;
                }
            }
            log.info("Original image was not found. Searching for recently uploaded");
            super.deleteFlatImage(flatImageType, secureId, persistenceManager);
        }
        finally {
            persistenceManager.close();
            if(flatAd != null && removed){
                cachingJdoFlatAdDao.removeFromCache(flatAd.getId());
            }
        }

    }

    private PersistenceManager getPersistenceManager() {
        return persistenceManagerFactory.getPersistenceManager();
    }

    @Required
    public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory) {
        this.persistenceManagerFactory = persistenceManagerFactory;
    }

    @Required
    public void setJdoHelper(JdoHelper jdoHelper) {
        this.jdoHelper = jdoHelper;
    }

    @Required
    public void setJdoFlatAdDao(JdoFlatAdDao jdoFlatAdDao) {
        this.jdoFlatAdDao = jdoFlatAdDao;
    }

    @Required
    public void setCachingJdoFlatAdDao(CachingJdoFlatAdDao cachingJdoFlatAdDao) {
        this.cachingJdoFlatAdDao = cachingJdoFlatAdDao;
    }
}
